package com.yyy.example;

import com.yyy.entity.Message;
import com.yyy.example.entity.User02;
import com.yyy.modules.MsgTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yyy
 * @Date 2020-09-13 16:28
 * @Email yangyouyuhd@163.com
 */
//@Component
@RestController
public class ProduceService {

    @Resource
    MsgTemplate msgTemplate;

    //    @PostConstruct
    public void init() {
        test一对多();
    }


    AtomicInteger[] arr = new AtomicInteger[3];

    /**
     * 轮询给多个队列发送消息
     */
    @RequestMapping("/more")
    public void test多对多() {
        String route = "queue0";
        for (int i = 1; i < 10; i++) {
            int num = i % 3;
            Object obj = arr[num] == null ? arr[num] = new AtomicInteger(1) : arr[num].incrementAndGet();
            msgTemplate.send(route + num, new User02("张三", i + 10, new Date()));
        }
    }

    @RequestMapping("/more/produceVal")
    public String moveResult() {
        return "一共给queue00发送了：" + arr[0] + "条消息" + "\n"
                + "一共给queue01发送了：" + arr[1] + "条消息" + "\n"
                + "一共给queue02发送了：" + arr[2] + "条消息";
    }


    AtomicInteger one = new AtomicInteger(0);

    /**
     * 给单个队列发送消息、该队列绑定了消息者集群
     */
    @RequestMapping("/one")
    public void test一对多() {
        System.out.println(Thread.currentThread().getName() + "模拟发送10条消息给一个queue04");
        String route = "queue04";
        for (int i = 1; i < 10; i++) {
            one.incrementAndGet();
            msgTemplate.send(route, new User02("张三", i + 10, new Date()));
        }
    }

    @RequestMapping("/one/produceVal")
    public String oneResult() {
        return "一共给queue04发送了：" + one.get() + "条消息";
    }


    @RequestMapping("/{name}")
    public String callback(@PathVariable("name") String name) {
        msgTemplate.send(name, new Message<>());
        return "给" + name + "发送了一条消息";
    }
}
